Lesson 3: Understanding Computer Programming - Chapter 1

Introduction

Welcome back! Today's lesson is all about programming. If you're new to all of this, don't be intimidated. We'll be taking it one step at a time. And remember, if you're feeling a little lost during this lesson (or any lesson), hop over to the Discussion Area, and I'll be more than happy to answer your questions there.

We'll begin today by exploring several essential tools of computer programming, including variables, loops, and branches. And then you'll work with the VS Design window to create the surface of your program, the UI. You'll see how to exploit some of the editor's great features to create an attractive and efficient interface window, and you'll learn some shortcuts, too.

Finally, in Chapter 4, we'll launch into some serious programming. It's pretty amazing how much you can accomplish with only a few lines of code. One reason is that VB has a lot of capabilities built into the language, so you often don't have to write code yourself to do a job. For example, to alphabetize all the recipes in the cookbook program, you just need to type in one word: sorted. And VB sorts them for you!

Ready to get started? I'll see you in Chapter 2.

Chapter 2

Discovering How Programs Work

Let's start by looking at some essential tools of computer programming. I mentioned variables, loops, and branches in the last chapter, so let's look at what these tools do.

  • Variables: These are similar to XML elements—they're both named containers of data.
  • Loops: Loops do a lot of the real work in programs. Essentially, a loop is a set of code lines that execute repeatedly until their job is done.
  • Branches: When a program branches, it makes a decision. Branching is how computers behave intelligently.

Have you noticed that your computer behaves intelligently? You might think of your computer as a tireless but highly literal super-servant. It has a limited vocabulary, but it'll follow your commands until you ask it to stop.

Working with commands is the cornerstone of VB programming. In your VB programming, you'll use these 15 commands most often:

  • Dim
  • String
  • Integer
  • For Each . . . Next
  • For . . . Next
  • While . . . End While
  • Do . . . Loop
  • If
  • Else
  • Select
  • Sub . . . End Sub
  • MsgBox
  • InputBox
  • End

Let's look at each of these in action.

  • Dim. Assigns a name to a variable. This is similar to the way you make up an XML tag name to describe an element's contents. In this line of code, I create a string variable that I've decided to name RecipesFilePath:
Dim RecipesFilePath As String
  • String. This is a variable that holds text. This example assigns a value (content) to a variable:
RecipesFilePath = "C:\XML Projects\cookbook\recipes.xml"

This value is a file path. It specifies where on your hard drive you can find the recipes.xml file. That's why I was smart to name it RecipesFilePath (if I do say so myself). Use descriptive variable names to make it easy to read your code.

  • Integer. This is a variable that holds whole numbers (like 12 or 1,552). Whole numbers have no decimal point. Here you create a numeric variable you want to call n for number. Once in a while it's okay to name variables n like this, or s for string, if it's really obvious what the variable is doing in your code:
Dim n As Integer
  • For Each...Next, For...Next, While...End While, and Do...Loop. These blocks of code are loops we discussed earlier. They execute a set of code lines repeatedly until a task is completed. The latter three are similar, with For...Next being the most common.
Tip

Blocks in a Computer Program

The word block means a set of programming lines that are grouped together, usually because they accomplish a single task. Sub . . . End Sub and If . . . Then are blocks of code, for example.

Here's how in the cookbook program you'll use a For...Each loop to add each recipe's title to a listbox that you named lstTitles:


For Each IndividualTitle In TheCollectionOfTitles

RecipeTitle = IndividualTitle.InnerText      

contentslstTitles.Items.Add(RecipeTitle)

Next recipe
  • If, Else, and Select. You use these commands to branch, which means to jump to different places in the code based on a test of current conditions. This is how computers make decisions. It's like the way you make decisions in real life—if it's raining, then put the cellphone in your pocket. That's one path, and the other path of this branch is to not put it in your pocket.
Here's an example of an If...End If block. When the cookbook program first starts running, it looks for the recipes.xml file on the user's hard drive. If it can't find the file (If Not in the code), that would mess up the rest of the program. So the program displays a message box that tells the user the file is missing, like this:

If Not My.Computer.FileSystem.FileExists(XMLFileName) Then 

             MsgBox("We were unable to open the cookbook's XML file: " & XMLFileName)

            End

End If

VB only executes these code lines (MsgBox and End) if the If statement is true. The If statement here states: If the filename does not exist, then show the MsgBox and End the program.

But if the file does exist, the program just skips over the code inside the If...End If block and continues executing whatever code lines that follow End If. This is why an If...Then block is an example of branching. The program takes one of two possible paths here: either executing the code lines within the If...Then section, or not.

Two Paths

Two Paths

  • Sub...End Sub. This command subdivides a program into manageable units of code.
  • MsgBox and InputBox. These commands display those small dialog windows like, "Do you really want to quit? Yes? No?"
  • End. The End command shuts down the program.

Memorizing Code

You might well be asking yourself: "Am I supposed to memorize all this?!"

Don't worry. The answer is, no. You aren't supposed to memorize it!

Some VB commands like If, Print, and End are so easy to remember you couldn't forget them if you wanted to. But others are longer, like that code that checks to see if a file exists. Just don't worry about them. You can almost always easily find example code by Googling.

Try it. Type into Google: VB does a file exist. The very first Web page that Google shows me is this example code from Microsoft:


If My.Computer.FileSystem.FileExists("c://Check.txt") Then

    MsgBox("File found.")

Else

    MsgBox("File not found.")

End If

Problem solved. All I had to do was replace their example's filepath, C://Check.txt, with mine, and get rid of that Else part that I don't need.

What's more, you often don't even have to Google, because as you type in your code, VB displays lists of commands and definitions automatically (check out the FAQs for examples of this). Or you can press F1 to open a huge online programmer's reference called MSDN, short for Microsoft Developer Network.

Here's a secret—I didn't remember how to write that file-exists code! And I have a fair amount of experience with VB, having programmed for 32 years and written 14 books on VB.

To be even more deeply honest, I don't remember most VB programming techniques. Why bother memorizing these things when it's so easy to look them up?

The Internet is loaded with VB programming advice and countless code examples that you can copy and paste into your projects. Then all you have to do is modify it a little (if you need to). I don't know about you, but I have enough other essential things to remember without filling my pretty head with unnecessary memories.

Chapter 3

Building a User Interface

Now that you know the fundamentals of VB code, let's add another component to the UI—a listbox control. A listbox control displays a list of items that the user can click. Then your program can respond to the user's selection. In our cookbook program, we'll show a list of all the recipe titles. When the user clicks one of them in the listbox, the program displays that recipe's instructions.

VB is called Visual Basic for a reason. You can just look in Toolbox for a UI component you want, and then you drop it onto your form. You don't have to write any code to create controls like buttons and listboxes. In VB, it's a pretty simple drag-and-drop.

Let's add a listbox control to the cookbook program now:

  1. Run VS.
  2. On the Start Page, locate the Recent header. Then double-click Cookbook. You'll see either the Code window or the Design window, depending on which was visible when you last shut VS down.
  3. If you're seeing the Code window, right-click a blank area in that window, and choose View Designer from the context menu.
  4. Click the Toolbox tab on the left side to display it.
  5. Double-click ListBox in the Toolbox to place a listbox on your form. Or you can drag and drop it into place.
  6.  
    ListBox in the Toolbox

    ListBox in the Toolbox

  7. Move your mouse away from the Toolbox to autohide it. Now you see the listbox on the upper-left corner of the form. (If you dragged it, you'll see it positioned where you dropped it.)

Great work! Here, take a look as I go through these steps with my cookbook program:


Chapter 3, Video 1:
"Adding a Listbox to the Cookbook's User Interface", TRANSCRIPT

Let's now add a listbox control to our Cookbook program. So start Visual Studio running and, as usual, locate the Recent header and find the project that you were working on last and that you want to work on now. Double-click that and it opens up. In this case, it's showing us the Design window. That's because that was the last window we were working in. But should you happen to see the Code window right now, it's easy enough to get here to the Design window. Just right-click in the Code window, and then choose View Designer from the context menu.

All right. Let's try to open the Toolbox up here by clicking on it, and let's go down to the listbox and double-click that. As soon as you move your mouse cursor outside the Toolbox it automatically closes, and there's our listbox.

But let me show you one more way to add a control to a form. I'll temporarily get rid of this listbox and we'll put one on now by dragging instead of double-clicking. So we'll go down to the listbox and drag it over onto the form, automatically closing the Toolbox and also at the same time allowing us to position the listbox anywhere we want to by releasing the left mouse button. And there it is.

END TRANSCRIPT

Remember that the purpose of this listbox is to allow the user to click one of the recipe titles and access the recipe's instructions. But the listbox won't be easy to use all tiny and lonely up there in the corner. This calls for a little UI designing.

Let's first make it larger so it'll display more titles.

  1. Start by dragging the listbox down until its bottom aligns with the bottom of the Exit button control. The editor displays a blue line when the two controls are aligned.
A line shows when controls align

A line shows when controls align

Users think that aligned controls look more professional, and they're right. You don't want your UI filled with components randomly askew! Of course you could align and position UI components by hand, eyeballing it—but why not take advantage of VB's shortcuts? In addition to the blue alignment lines, VB offers several more alignment tools. Let's look at them.

  1. Group the listbox and exit button by holding down SHIFT while clicking each control. They'll both display a dotted frame with six tiny selection squares. 
  2. Alternatively, group them by dragging your mouse on the form to create a frame around both controls, and then release the mouse button.
A frame around ListBox1 and the Exit button

A frame around ListBox1 and the Exit button

You'll find even more tools for UI alignment and design in the Format menu.

 
Alignment tools in the Format menu

Alignment tools in the Format menu

By grouping controls, you can modify them as a unit, rather than individually. You can also reposition the grouped listbox and button at the same time by dragging just one of them. Or you can resize them by dragging a selection square on just one of the controls.

If you change a value like text size in the Properties window, the text size of all the grouped controls changes. (When you group controls, the Properties window displays only the properties that the controls have in common.)

Tip

Grouping Limits

There's no limit to grouping. If you want to change the color of 12 buttons all at once, just group them and choose their new color in the Properties window. Done!

Let's make both the listbox and the exit button display size 12 text.

  1. While the controls are grouped, click the font property in the Properties window.
  2. Then click the small, boxed ellipsis that appears next to the font property.
  3. Choose 12 as the Font Size in the Font dialog box, and then click OK
  4. Both now have a larger, more readable text size. Nice work. Our final UI job is to enlarge the listbox.

  5. Click the background of the form to ungroup the controls.
  6. Click the listbox to select it. Using one of its corner drag handles, drag the listbox to make it about as large as you see here:
Enlarged listbox

Enlarged listbox

Now your listbox is tall enough to display plenty of recipe titles and wide enough so even the longest title will show.

Notice in the screen shot how I've positioned the listbox so it's the same distance on three of its sides from the edge of the form. And the button is similarly spaced that same distance from the sides of the form. This is yet another visual uniformity that says to your users, "Hey, this looks professional. This program is reliable and solidly built throughout. Whoever did this deserves a raise!"

Tip

Fine-tune Spacing

Here's a great way to fine-tune a control's spacing: Select the listbox, and then use the arrow keys to move it slowly around until it looks just right.

One final job.

  1. Click the listbox to select it, and then in the Properties window, change its Name property from the default Listbox1 to lstTitles. lstTitles is how you'll refer to it in your programming code.
  2. Press ALT + F4 to close VS, and click the Yes button when asked if you want to save your work.

All right, looking good. Now it's time to go behind the Design window and write the code that will fill this listbox with recipe titles.

Chapter 4

Adding Source Code

Let's do some programming! Remember, you don't need to memorize this VB code, or even understand it completely. Your goal right now is simply to get comfortable with some elements of VB programming.

First up, let's start VS running so you can paste this lesson's programming code into it. Then we'll take a look at the code to see how it does its job. Follow these steps:

  1. Open Windows Explorer, and locate the C:XML Projects\Cookbook folder.
  2. Double-click the cookbook.sln file.
Tip

Add a Shortcut to Your Cookbook Program

You'll be opening the cookbook program quite often during this course, so why not make life easier by creating a desktop shortcut? Then in the future, you can just double-click that shortcut on your Windows desktop to quickly open the cookbook in the VB editor.

It's easy to create a shortcut: Right-click the cookbook.sln file in Windows Explorer, and then click Send To > Desktop (create shortcut) in the context menu:

Context menu with desktop shortcut option

Context menu with desktop shortcut option

  1. Open the Code window by double-clicking  an empty area in the form background in the Design window. (In other words, don't click one of the controls; instead, click the form itself.) The Code window opens, and VB automatically adds a Form_Load sub.
Code window with sub added

Code window with sub added

  1. Now select the following code by holding down the left mouse button and dragging the mouse over the code here in this lesson:

        Dim TheCollectionOfTitles As XmlNodeList

        Dim IndividualTitle As XmlNode

        Dim RecipeTitle As String

        doc = New XmlDocument()

        doc.Load(RecipesFilePath)

        lstTitles.Sorted = True

        If Not My.Computer.FileSystem.FileExists(RecipesFilePath) Then

            MsgBox("We were unable to open the cookbook's XML file: " & RecipesFilePath)

            End

        End If

        TheCollectionOfTitles = doc.GetElementsByTagName("title")

        For Each IndividualTitle In TheCollectionOfTitles

            RecipeTitle = IndividualTitle.InnerText

            lstTitles.Items.Add(RecipeTitle)

        Next IndividualTitle

Got it selected? Great! Now we just want to copy and paste.

  1. Press CTRL + C to copy the selected code.
  2. Now go to the editor's Code window, click your mouse just below the Form_Load line. It looks like this:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

By clicking just below this line, you're telling the editor that you want to paste right here.

  1. Press CTRL + V to paste the code into the Form_Load event.

How did you do? Take a look here as I walk through these steps. And don't worry about all those sawtooth error lines. We'll fix that in a minute!


Chapter 4, Video 1:
"Copying Code From the Internet and Pasting It Into Visual Studio", TRANSCRIPT

We now want to copy some code from the browser to Visual Studio. So first, let's move to the Code window. You locate a spot somewhere on the blank form, not in one of the controls, but on the blank form, and double-click it, and there you are in the Code window. Now, this blinking insertion cursor here indicates where something pasted will go in the Code window, or for that matter, something that you type.

So let's go over to the browser by pressing Alt, Tab, which moves you quickly between programs in Windows, and here we are in the browser with this lesson code in it. Now, to copy the code, just hold down the left mouse button and select the code by moving down until you get to the bottom, and it's all selected. And to copy it now to the clipboard, press Control, C. Okay, Alt, Tab back to the Code window and all you do to paste it in is press Control, V, and there it is

END TRANSCRIPT

Next up, default events . . .

Understanding Default Events

When you double-click in the Design window, VB takes you to the Code window. And VB then automatically adds whichever sub is the most commonly used event for the control you clicked. An event (or sub) is something that happens while a program is running (for example, a timer counts down to 0, or the user types something or clicks a button). Most controls have many events that can happen to them, such as click, dragdrop, textchanged, mousewheel, and so on.

And most VB programming code (or source code) is written inside events, because you need to tell the program what to do when one of these events happens. Think of this as similar to telling a rookie coach exactly how to act in various situations—a player gets injured, or a fan freaks out and runs onto the field, or the team revolts. You get the idea.

When you double-clicked your form in the Design window a few minutes ago, the Code window opened and automatically created a Form_Load event. For a form, the Load event is the most common sub. So VB creates that sub when you double-click a form.

Almost every VB program contains a Form_Load event. When a program first starts running, VB will execute any lines of code you've written between the Sub Form_Load and End Sub. VB executes this code before the program even shows the form to the user.

What Does Load Mean in Computerese?

Load means to copy a program (or file) from the hard drive (long-term memory) into the computer's RAM (short-term memory). RAM runs far faster than a hard drive. But the hard drive is much larger than RAM, so it holds lots of programs and other data.

The first thing the cookbook program needs to do is display a list of all the recipe titles. You can write that code here in Form_Load.

Here are the six tasks you want VB to do in your cookbook program's Form_Load event:

  • Declare an object to hold a collection of all the title elements.
  • Declare another object to hold an individual title element.
  • Declare an ordinary string variable to hold the contents of an individual title element.
  • Load all the recipes from the recipes.xml file on your hard drive into the computer's memory so the cookbook program can easily work with them.
  • Display all the recipe titles in a listbox.
  • Alphabetize the titles in the listbox.

Sounds like a lot of code. But guess how many lines of code you'll need to write accomplish these six tasks?

15 Lines of code

15 Lines of code

Tip

Collections

Take another look at the first item in that list of six tasks. Did you notice the new command called collection? That's a set of related objects that you can manipulate as a unit.

Once grouped together, you can easily go through the collection of objects one-by-one by using a For...Next loop. You'll do exactly that in the cookbook program's Form_Load event to fill the listbox with the recipe titles.

Some Interesting Programming

Now let's translate what VB is doing in some interesting parts of this sub. Most subs start with any necessary Dim statements. If you'll remember, a Dim statement creates a variable. This sub needs three variables:

        Dim RecipeTitle As String

        Dim TheCollectionOfTitles As XmlNodeList

        Dim IndividualTitle As XmlNode

First, you declare an ordinary string variable that you name RecipeTitle. This variable will hold text like Spaghetti, or The Secret to Perfect Coleslaw, or whatever the content happens to be in the title element you're working with at the time the code executes. This explains why they're called variables. The contents in a variable can vary or change while a program runs. It doesn't have to change, but it can.

The other two items you Dim here are objects, but you can think of them as a kind of super-variable. Objects can hold multiple values (an ordinary variable only holds a single value—like the number 17 or the text car parts.)

  • The XMLNodeList object (I named it TheCollectionOfTitles) will hold a collection of all the <title> elements in the whole recipes file. (The word node is just another word for element in this context.)
  • The XMLNode object (I named it IndividualTitle) holds an individual <title> element. As the program runs, this object holds whatever particular title element the code is working with at the time.

Think of the XMLNodeList and XMLNode objects as containers—similar to variables, but larger and more capable. They can contain many XML elements at once.


   doc = New XmlDocument()

   doc.Load(RecipesFilePath)

These two lines of code bring to life the object we're calling doc. The first line declares that this is an XML document container. The Doc object will hold your entire recipes.xml document! Now you know why an object is like a super-variable.

The next code line, doc.Load(RecipesFilePath), copies the recipes.xml file from the hard drive into the doc object in RAM memory. It's like the way that the Form_Load event copies the cookbook program from the hard drive into RAM. In both cases, you load these things because RAM is so much faster than a hard drive.

From now on, when you refer to doc in your code, you can access any of the elements and contents of recipes.xml!

Adding Some Housekeeping Code

All right, let's do a little housekeeping. We're going to add three lines of code at the top of the Code window, above the subs. This way, all of the subs in the program can use them.

Type these boldface lines into the editor, as indicated:


Imports System.Xml

Public Class Form1

    Dim RecipesFilePath As String = "C:\XML Projects\cookbook\recipes.xml"

    Dim doc As XmlDocument

The Imports statement refers to a whole library of useful XML commands. The two Dim statements tell the program where our recipes.xml file is located (and that the variable doc is an XmlDocument). Several subs in the program need to use the file path and the doc object, so rather than repeatedly creating them in each sub, you can just put them up here and any sub can then access them. Variables declared up top like this are what we call global variables (as opposed to the local variables declared within subs).


Testing the Code

To test the cookbook program properly, you'll want to have more than just one recipe in the recipes.xml document. Follow these steps to replace your current recipes.xml file with the new version that has two new dishes:

  1. Click the button below to download the new version of the recipes.xml file.
  2. Using Windows Explorer (AKA File Explorer), locate the new recipes.zip file you just downloaded. (Only you know where downloads are saved on your hard drive. By default, they go to the YourName > Downloads folder, but I usually send them to my desktop.)
  3. Right-click Recipes.zip. A dialog box opens.
  4. Click the Extract button in the dialog box.
  5. Right-click the new, downloaded recipes.xml file, and choose Copy from the context menu.
  6. Navigate to your C:\XML Projects\cookbook folder (where the old recipes.xml file is stored).
  7. Press CTRL + V to paste the new recipes.xml file into the C:\XML Projects\cookbook folder. A dialog box opens, asking if you really want to replace this file.
  8. Click Replace the file in the destination.

Okay, you're now ready to test the code you added to the Form_Load sub in this lesson. Press F5 in the editor to run the cookbook program. It should fill the listbox with three recipe titles and look like this:

Voila! Your program works as planned

Voila! Your program works as planned

If something doesn't work right, take a look at the tips in the FAQs section.

Let's Chat!

Also, I showed you how to use the arrow keys to fine-tune the position of buttons and other controls on a form. The editor is full of dozens of great tools and tricks like this. If you've discovered any of them on your own, let us know in the Discussion Area. This is the place to share your findings with your classmates!

Remember, you don't have to memorize code (unless you have a photographic memory and can't help it). My goal is to give you the tools you'll need to eventually write your own code. And that simply means feeling comfortable using the editor's Design and Code windows, knowing where to look for sample code on the Internet, and accepting the fact that we programmers rarely get it right the first time.

When you program, it's not like writing a postcard to a friend. You're instructing a very literal machine. (If you told a computer that you saw a really cool movie, it would think "air-conditioned theater.")

But if you have a lingering question about this code, or anything else in this lesson, please let me know in the Discussion Area!